from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from extensions import db
from models import Category
from utils.response import success_response, error_response

api = Blueprint('category_api', __name__)


@api.route('/', methods=['GET'])
@jwt_required()
def get_categories():
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)
    query = Category.query
    total = query.count()
    categories = query.offset((page - 1) * limit).limit(limit).all()
    return jsonify({
        'code': 0,
        'msg': 'success',
        'count': total,
        'data': [c.to_dict() for c in categories]
    })



@api.route('/', methods=['POST'])
@jwt_required()
def add_category():
    name = request.form.get('name', '').strip()
    description = request.form.get('description', '').strip()

    if not name:
        return jsonify(error_response('分类名称不能为空')), 400

    cat = Category(name=name, description=description)
    db.session.add(cat)
    db.session.commit()
    return jsonify(success_response({'category': cat.to_dict()}, msg='添加成功'))


@api.route('/<int:category_id>', methods=['POST'])
@jwt_required()
def update_category(category_id):
    cat = Category.query.get_or_404(category_id)
    name = request.form.get('name', '').strip()
    description = request.form.get('description', '').strip()

    if name:
        cat.name = name
        cat.description = description
        db.session.commit()

    return jsonify(success_response({'category': cat.to_dict()}, msg='更新成功'))


@api.route('/<int:category_id>', methods=['DELETE'])
@jwt_required()
def delete_category(category_id):
    cat = Category.query.get_or_404(category_id)

    for site in cat.websites:
        db.session.delete(site)
    db.session.delete(cat)
    db.session.commit()

    return jsonify(success_response(msg='删除成功'))
